package com.huluobo.a2303mdmdemo.goods.pages

import android.util.Log
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2303mdmdemo.goods.GoodsIntent
import com.huluobo.a2303mdmdemo.goods.GoodsViewModel
import com.huluobo.a2303mdmdemo.goods.entity.CartEntityItem
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/9/3.
 */

@Composable
fun CartPage(navHostController: NavHostController, vm: GoodsViewModel = hiltViewModel()) {
    // 使用 remember 来保存可观察的状态
    val list = remember { mutableStateListOf<CartEntityItem>() }
    var isShowProgress by remember { mutableStateOf(false) }
    var allSelected by remember { mutableStateOf(false) }

    // 监听选择状态变化
    LaunchedEffect(list) {
        allSelected = list.isNotEmpty() && list.all { it.isCheck }
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnFailed -> {
                        isShowProgress = false
                        ToastUtils.showLong("获取购物车列表失败:${it.msg}")
                        Log.e("TagA", "获取购物车列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {
                        isShowProgress = true
                    }

                    is UIState.OnSuccess<*> -> {
                        isShowProgress = false
                        list.clear()
                        // 确保每个项目都有正确的初始状态
                        (it.data as? List<CartEntityItem>)?.forEach { item ->
                            list.add(item.copy())
                        }
                        Log.e("TagA", "cart:${list.size}")
                    }
                }
            }
        }
        vm.sendIntent(GoodsIntent.GetAllCart)
    })

    Column(
        modifier = Modifier.padding(10.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        BaseTitle(title = "购物车", navHostController = navHostController)

        // 顶部操作栏
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 全选/取消全选
            Row(verticalAlignment = Alignment.CenterVertically) {
                IconButton(onClick = {
                    val newState = !allSelected
                    list.forEachIndexed { index, item ->
                        list[index] = item.copy(isCheck = newState)
                    }
                    allSelected = newState
                }) {
                    Icon(
                        imageVector = if (allSelected) Icons.Default.Check else Icons.Default.Close,
                        contentDescription = "全选"
                    )
                }
                Text("全选")
            }

            // 删除选中
            IconButton(onClick = {
                // 这里实现删除选中的逻辑
                val selectedItems = list.filter { it.isCheck }
                ToastUtils.showShort("删除 ${selectedItems.size} 个商品")
            }) {
                Icon(Icons.Default.Delete, contentDescription = "删除")
            }
        }

        // 选中数量显示
        val selectedCount = list.count { it.isCheck }
        if (selectedCount > 0) {
            Text(
                text = "已选择 $selectedCount 件商品",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.primary
            )
        }

        LazyColumn(
            content = {
                items(list) { item ->
                    CartItem(
                        entityItem = item,
                        onCheckedChange = { isChecked ->
                            val index = list.indexOfFirst { it.id == item.id }
                            if (index != -1) {
                                list[index] = item.copy(isCheck = isChecked)
                            }
                        }
                    )
                }
            },
            verticalArrangement = Arrangement.spacedBy(10.dp)
        )

        // 底部结算栏
        if (list.isNotEmpty()) {
            Surface(
                modifier = Modifier.fillMaxWidth()
            ) {
                Row(
                    modifier = Modifier.padding(16.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "合计: ¥${list.filter { it.isCheck }.sumOf { it.goods_default_price * it.count }}",
                    )

                    Button(
                        onClick = {
                            ToastUtils.showShort("结算 ${selectedCount} 件商品")
                        },
                        enabled = selectedCount > 0
                    ) {
                        Text("结算($selectedCount)")
                    }
                }
            }
        }
    }
}

@Composable
fun CartItem(entityItem: CartEntityItem, onCheckedChange: (Boolean) -> Unit) {
    Card(
        modifier = Modifier.fillMaxWidth(),
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Checkbox(
                checked = entityItem.isCheck,
                onCheckedChange = onCheckedChange
            )

            AsyncImage(
                model = entityItem.goods_default_icon,
                contentDescription = "",
                modifier = Modifier.size(80.dp)
            )

            Column(
                modifier = Modifier
                    .height(80.dp)
                    .weight(1f)
                    .padding(horizontal = 8.dp),
                verticalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = entityItem.goods_desc,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                    style = MaterialTheme.typography.bodyLarge
                )

                Text(
                    text = "¥${entityItem.goods_default_price}",
                )

                Text(
                    text = "数量: ${entityItem.count}",
                )
            }
        }
    }
}